<script>
import RenderUtils from './RenderUtils';
import {deepClone} from '../../utils';
import {SelectConfig, TableConfig,} from '../dynamic-table/TableType';
import {FormConfig} from '../dynamic-form/ConfigType';
import typeOfUtils from '../../utils/type-of-utils';
import emitter from 'element-ui/src/mixins/emitter'; // 分发事件的el-form处理方法
import {SelectObjectMixin} from "../../mixins/SelectObjectMixin";

export default {
  name: 'SelectObject',
  // 定义用到的组件
  components: {
    DynamicForm: () => import('../dynamic-form'),
    DynamicTable: () => import('../dynamic-table'),
  },
  // 过滤器
  filters: {},
  // 定义用到的混入，可以重复使用代码
  mixins: [emitter,SelectObjectMixin],
  // 属性定义使用对象的形式进行定义
  props: {
    layout: {
      type: String,
      default: 'top-left-right', // left-right 左右结构， top-left-right 上 左右结构
    },
    rightSlot: {
      type: Boolean,
      default: false, // 右侧渲染插槽
    },
    placeholder: {
      // showType为button显示到按钮上
      type: String,
      default: '请选择',
    },
    rightPlaceholder: {
      type: String,
      default: '请输入关键字过滤',
    },
    width: {
      type: String,
      default: '80%',
    },
    config: {
      // 表格和表单结合
      type: Array,
      default: () => [],
      required: true,
    },
    selectConfig: {
      // 选择配置
      type: SelectConfig,
      default: () => {},
    },
    showIndex: {
      type: Boolean, // 显示序号
      default: false,
    },
    indexConfig: {
      type: Object,
      default: () => {
        return {
          indexFirstNumber: 0, // 序号起始值 表格index+indexFirstNumber
        };
      },
    },
    showLoadAgain: Boolean, // 是否每次显示都重新加载
    tableMergeConfig: Function, // 表格合并配置，如果这个有值，就全部交个自己配置
    asyncSetTableData: {
      // 异步设置表格数据
      type: Function, // 参数：表单数据， 分页数据 返回：promise 结果用于表格显示
      required: true,
    },
    showType: {
      // 显示的控件 如果是插槽 插槽名称为 showSlot 参数{disabled,showFunc}
      type: String,
      default: 'input', // input button slot
    },
    clearSelectObjects: Boolean, // 关闭是否清空选中的值
    formOtherItems: {
      // 表单items的配置，在config后面
      type: Array,
      default: () => [],
    },
    formConfigProps: {
      // 表单的配置
      type: Object,
      default: () => {},
    },
    clearFormData: Boolean, // 清除表单数据
    clearFormDataInOpened: Boolean, // 弹窗的时候清除表单数据
  },
  // 定义变量
  data() {
    return {
      formConfig: {},
      tableConfig: [],
      searchForm: {},
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 50,
      tableData: [],
      loading: false,
      oldSelectData: [], // 存一份旧数据，表格选中的数据
    };
  },
  render(createElement, context) {
    const children = [];
    if (this.showType === 'button') {
      children.push(...RenderUtils.renderButton(this, createElement));
    } else if (this.showType === 'slot') {
      children.push(...RenderUtils.renderShowSlot(this, createElement));
    } else {
      children.push(...RenderUtils.renderInput(this, createElement));
    }
    children.push(...RenderUtils.renderSelect(this, createElement)); // 渲染选择器
    return createElement(
      'div',
      {
        class: {
          selectObject: !this.disabled,
        },
      },
      children
    );
  },
  // 定义计算属性值，加上watch配合，可以读取vuex异步获取的值
  computed: {
    inputShowValue() {
      return this.showSelectData.map((i) => this.selectShowView(i)).join('/');
    },
    tableHeight() {
      return window.innerHeight / 2;
    },
    showSelectData({ value, dragDialogShow }) {
      let result = [];
      if (typeOfUtils.isFunction(this.tableMergeConfig)) {
        result = this.getTableMergeConfig.showSelectData(this.selectData);
      } else {
        result = this.selectData;
      }
      return result.filter((i) => {
        if (this.selectMultiple) {
          if (this.selectShowView(i).includes(this.filter)) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      });
    },
    getTableMergeConfig() {
      if (typeOfUtils.isFunction(this.tableMergeConfig)) {
        return this.tableMergeConfig(this.tableData, this);
      }
      return {};
    },
  },
  watch:{
    dragDialogShow(val) {
      if (val) {
        this.$refs.dialogWrapRef.open()
      } else {
        this.$refs.dialogWrapRef.close()
      }
    }
  },
  // 生命周期钩子函数begin
  // 在页面节点挂载完执行
  mounted() {
    this.dragDialogShow = this.$refs.dialogWrapRef.visible
  },
  // 在页面创建完执行
  created() {
    this.initConfig();
    this._initSelectData()
  },
  // 生命周期钩子函数end
  // 定义方法
  methods: {
    _valueRefChange(val, old){
      this.dispatch('ElFormItem', 'el.form.change', val);
    },
    _initSelectData() {
      if (typeOfUtils.isArray(this.value)) {
        this.$set(this, 'selectData', this.value);
      } else {
        this.selectData.splice(0, this.selectData.length)
        if (typeOfUtils.isNotEmpty(this.value)) {
          this.selectData.push(this.value);
        }
      }
    },
    _clearSelect() {
      this.selectData.splice(0, this.selectData.length)
      const table = this.$refs.DynamicTableRef;
      if (table) {
        this.$nextTick(() => {
          if (this.selectMultiple) {
            table.$refs.elTableRef.clearSelection();
          } else {
            table.zhixinRadio = undefined;
          }
        });
      }
    },
    _setRowSelect() {
      const table = this.$refs.DynamicTableRef;
      if (table) {
        // 处理第一个加载的时候组件没有加载出来
        // 数据切换要进行回显
        if (this.selectMultiple) {
          this.$nextTick(() => {
            this.tableData.forEach((newItem) => {
              const row = this.selectData.find((oldItem) =>
                this.selectEquals(oldItem, newItem)
              );
              if (row) {
                table.$refs.elTableRef.toggleRowSelection(newItem, true);
              } else {
                table.$refs.elTableRef.toggleRowSelection(newItem, false);
              }
            });
          });
        } else {
          if (typeOfUtils.isFunction(this.tableMergeConfig)) {
            if (typeOfUtils.isNotEmpty(this.selectData)) {
              if (
                typeOfUtils.isFunction(
                  this.getTableMergeConfig.singleTableSelectShow
                )
              ) {
                table.zhixinRadio =
                  this.getTableMergeConfig.singleTableSelectShow(
                    this.selectData,
                    this.tableData
                  );
              } else {
                // 给一个默认实现。使用eltable工具就可以
                const findIndex = this.tableData.findIndex((newItem) =>
                  this.selectEquals(this.selectData[0], newItem)
                );
                if (findIndex > -1) {
                  table.zhixinRadio = findIndex;
                } else {
                  table.zhixinRadio = undefined;
                }
              }
            }
          } else {
            this.selectData.forEach((oldItem) => {
              const findIndex = this.tableData.findIndex((newItem) =>
                this.selectEquals(oldItem, newItem)
              );
              if (findIndex > -1) {
                table.zhixinRadio = findIndex;
              } else {
                table.zhixinRadio = undefined;
              }
            });
          }
        }
      }
    },
    initTableData() {
      this.loading = true;
      this.asyncSetTableData(this.searchForm, this.page)
        .then(({ data, total }) => {
          this.tableData = data;
          this.total = total;
          this._setRowSelect();
          this.oldSelectData = []; // 数据更新
        })
        .finally(() => {
          this.loading = false;
        });
    },
    initConfig() {
      this.tableConfig = new TableConfig({}, deepClone(this.config));
      const formitems = [
        ...this._getFormItems(this.config),
        ...this.formOtherItems,
      ];
      this.formConfig = new FormConfig(
        {
          ...this.formConfigProps,
          inline: true,
          labelPosition: 'right',
        },
        formitems
      );
      if (typeOfUtils.isFunction(this.tableMergeConfig)) {
        if (this.getTableMergeConfig.pageSize) {
          this.page.pageSize = this.getTableMergeConfig.pageSize;
        }
      }
    },
    _getFormItems(config = []) {
      const result = [];
      config.forEach((i) => {
        if (typeOfUtils.isNotEmpty(i.search)) {
          result.push({
            label: i.label,
            prop: i.prop,
            ...i.search,
          });
        }
        if (i.children) {
          result.push(...this._getFormItems(i.children));
        }
      });
      return result;
    },
  },
};
</script>
<style scoped lang="scss">
.select-object-dialog {
  ::v-deep {
    .el-dialog__body {
      border-bottom: 1px solid #E7ECF1;
      padding: 30px 20px 20px;
    }
  }
}
.select-content{
  position:relative;
  margin-bottom: 10px;
}
.DynamicForm{
  // border-bottom: 1px solid #E7ECF1;
  // margin-bottom: 20px;
}
.DynamicTable{
  margin-bottom: 29px;
}
.rightContent{
  position: absolute;
  right: 0;
  height: 100%;
  border: 1px solid #E7ECF1;
  border-radius: 4px;
  overflow-y: auto;
  .resultCount{
    height: 32px;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .filterInput{
    height: 32px;
    ::v-deep{
      .el-input__validateIcon{
        display: none;
      }
    }
  }
  ::v-deep {
    .el-scrollbar {
      height: calc(100% - 52px);
      width: 100%;
      .el-scrollbar__wrap {
        overflow-x: hidden;
      }
    }
    .el-tag{
      display: block;
      width: 100%;
      border: none;
      border-bottom: 1px solid #E7ECF1;
      padding-top: 10px;
      padding-bottom: 10px;
      margin-left: 0;
      padding-left: 8px;
      height: auto;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      position: relative;
      padding-right: 16px;
      &:hover{
        background-color: rgba(24, 109, 209, 0.15);
      }
      .el-icon-close{
        position: absolute;
        top: 25%;
        right: 4px;
        color: #97989F;
        background-color: #E4E5EB;
        &:hover{
          color: #FFF;
          background-color: #409eff;
        }
      }
    }
  }
}

// ::v-deep .el-table__body-wrapper{
//   height: 470px;
//   overflow-y: auto;
// }
@media screen and (max-width: 1366px) {
  ::v-deep .el-table__body-wrapper{
    height: 225px;
    overflow-y: auto;
  }
}

@media screen and (min-width: 1440px) and (max-width: 1600px) {
  ::v-deep .el-table__body-wrapper{
    height: 400px;
    overflow-y: auto;
  }
}

@media screen and (min-width: 1601px) {
  ::v-deep .el-table__body-wrapper{
    height: 550px;
    overflow-y: auto;
  }
}
</style>
